package com.lanou3g.multi_mybatis.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.lanou3g.multi_mybatis.mapper.taotao", sqlSessionTemplateRef  = "taotaoSqlSessionTemplate")
public class TaotaoDataSourceConf {
	
	@Bean("taotaoDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.taotao")
	public DataSource taotaoDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean("taotaoSessionFactory")
	public SqlSessionFactory taotaoSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(taotaoDataSource());
		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/taotao/*.xml"));
		return factoryBean.getObject();
	}

	@Bean("taotaoTxManager")
	public DataSourceTransactionManager taotaoTxMananger() {
		return new DataSourceTransactionManager(taotaoDataSource());
	}

	@Bean("taotaoSqlSessionTemplate")
	public SqlSessionTemplate taotaoSqlSessionTempate() throws Exception {
		return new SqlSessionTemplate(taotaoSqlSessionFactory());
	}
}
